package com.ruoyi.ring.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.TimeUnitEnums;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.ring.domain.RingExerciseDetail;
import com.ruoyi.ring.domain.RingHeartRate;
import com.ruoyi.ring.domain.RingHeartRateInfo;
import com.ruoyi.ring.domain.RingSleepDetail;
import com.ruoyi.ring.domain.dto.GeneralSecondDTO;
import com.ruoyi.ring.domain.dto.RingHeartRateInfoDTO;
import com.ruoyi.ring.domain.dto.RingSleepDetailInfoDTO;
import com.ruoyi.ring.domain.vo.*;
import com.ruoyi.ring.mapper.RingExerciseDetailMapper;
import com.ruoyi.ring.mapper.RingHeartRateInfoMapper;
import com.ruoyi.ring.mapper.RingHeartRateMapper;
import com.ruoyi.ring.mapper.RingSleepDetailMapper;
import com.ruoyi.ring.service.IHeartRateSecondService;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class HeartRateSecondServiceImpl implements IHeartRateSecondService {
    @Resource
    private RingSleepDetailMapper sleepDetailMapper;
    @Resource
    private RingHeartRateInfoMapper ringHeartRateInfoMapper;
    @Resource
    private RingHeartRateMapper heartRateMapper;
    @Resource
    private RingHeartRateInfoMapper heartRateInfoMapper;
    @Resource
    private RingExerciseDetailMapper exerciseDetailMapper;
    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public List<CalendarResultVO> queryCalendarList(GeneralSecondDTO secondDTO) {
        List<RingHeartRateInfo> heartRateInfoList = heartRateInfoMapper.selectRingHeartRateInfoList(Builder.of(RingHeartRateInfo::new).with(RingHeartRateInfo::setDeviceSn,secondDTO.getDeviceSn()).build());
        List<CalendarResultVO> resultVOS = Convert.toList(CalendarResultVO.class,heartRateInfoList);
        ZoneId zoneId = ZoneId.systemDefault();
        List<CalendarResultVO> list = resultVOS.stream()
                .collect(Collectors.toMap(
                        vo -> vo.getDailyValue().toInstant().atZone(zoneId).toLocalDate(),
                        Function.identity(),
                        (existing, replacement) -> existing
                ))
                .values()
                .stream()
                // 使用Comparator.comparing指定按日期正序
                .sorted(Comparator.comparing(vo -> vo.getDailyValue().toInstant().atZone(zoneId).toLocalDate()))
                .collect(Collectors.toList());
        return list;
    }
    @Override
    public GeneralAverageVO queryHeartRateAverage(GeneralSecondDTO secondDTO) {
        GeneralAverageVO averageVO = new GeneralAverageVO();
        //自动测量
        List<RingHeartRateInfo> heartRateInfoList = heartRateInfoMapper.queryRingHeartRateInfoList(Builder.of(RingHeartRateInfoDTO::new).
                        with(RingHeartRateInfoDTO::setDeviceSn, secondDTO.getDeviceSn()).
                        with(RingHeartRateInfoDTO::setHistoryDay, secondDTO.getRecordDate()).
                        with(RingHeartRateInfoDTO::setType, secondDTO.getType()).build());
        List<Integer> infoList = new ArrayList<>();
        int average = 0;
        int maxValue;
        int minValue;
        List<GeneralAverageVO.ManualInfoVO> manualInfoVOList = new ArrayList<>();
        List<GeneralAverageVO.AutomaticInfoVO> automaticInfoVOList = new ArrayList<>();
        if("1".equals(secondDTO.getType())){ //睡眠信息
            RingSleepDetail sleepDetail = sleepDetailMapper.querySleepInfoDetail(Builder.of(RingSleepDetailInfoDTO::new).
                    with(RingSleepDetailInfoDTO::setDeviceSn, secondDTO.getDeviceSn()).
                    with(RingSleepDetailInfoDTO::setDailyValue, secondDTO.getRecordDate()).build());
            if(sleepDetail != null) {
                averageVO.setEndTime(DateUtils.convertDateTimeToHHMM(sleepDetail.getEndDate()));
            }
            if(heartRateInfoList.size() > 0) {
                RingHeartRateInfo ringHeartRateInfo = heartRateInfoList.get(0);
                String[] infos = ringHeartRateInfo.getHeartRateList().replace("null", "0").replace("255", "0").split(",");//转成String数组
                infoList = Arrays.stream(infos).map(Integer::parseInt).collect(Collectors.toList());
                average = Convert.toInt(infoList.stream().filter(num -> num != 0).mapToInt(Integer::intValue).average().orElse(0.0));
                int timeInterval = 24*60/infoList.size();
                for(int i = 0; i< infoList.size(); i++){
                    GeneralAverageVO.AutomaticInfoVO automaticInfoVO = new GeneralAverageVO.AutomaticInfoVO();
                    int bo = infoList.get(i);
                    // 计算当前时间（分钟）：初始0分钟，每次增加5分钟
                    int minutes = i * timeInterval;
                    // 格式化时间为HH:MM格式（补前导零）
                    automaticInfoVO.setCode(DateUtils.convertMinutesToHHMM(minutes));
                    automaticInfoVO.setValue(bo);
                    automaticInfoVOList.add(automaticInfoVO);
                }
            }
            //手动测量
            List<RingHeartRate> ringHeartRateList = heartRateMapper.queryHeartRateList(secondDTO);
            for (RingHeartRate detail : ringHeartRateList){
                int value = detail.getHeartRate();
                GeneralAverageVO.ManualInfoVO manualInfoVO = new GeneralAverageVO.ManualInfoVO();
                manualInfoVO.setCode(DateUtils.convertDateTimeToHHMM(detail.getEndTime()));
                manualInfoVO.setValue(Convert.toStr(value));
                manualInfoVOList.add(manualInfoVO);
                infoList.add(value);
            }
            maxValue = infoList.stream().filter(num -> num != 0).max(Integer::compare).orElse(0);
            minValue = infoList.stream().filter(num -> num != 0).min(Integer::compare).orElse(0);
            averageVO.setMaxValue(maxValue);
            averageVO.setMinValue(minValue);
            averageVO.setRecordDate(DateUtils.dateTimeChinese(secondDTO.getRecordDate()));
            averageVO.setWeekName(DateUtils.queryWeekday(secondDTO.getRecordDate()));
        }else {
            List<Integer> total = new ArrayList<>();
            for (RingHeartRateInfo ringHeartRateInfo : heartRateInfoList){
                GeneralAverageVO.AutomaticInfoVO automaticInfoVO = new GeneralAverageVO.AutomaticInfoVO();
                String[] strs = ringHeartRateInfo.getHeartRateList().replace("null", "0").replace("255", "0").split(",");//转成String数组
                List<Integer> ringHeartRateInfos = Arrays.stream(strs).map(Integer::parseInt).collect(Collectors.toList());
                total.addAll(ringHeartRateInfos);
                if("2".equals(secondDTO.getType())) automaticInfoVO.setCode(DateUtils.convertDateToMMdd(ringHeartRateInfo.getDailyValue()));
                if("3".equals(secondDTO.getType())) automaticInfoVO.setCode(DateUtils.queryMonthday(ringHeartRateInfo.getDailyValue()));
                maxValue = ringHeartRateInfos.stream().filter(num -> num != 0).max(Integer::compare).orElse(0);
                minValue = ringHeartRateInfos.stream().filter(num -> num != 0).min(Integer::compare).orElse(0);
                automaticInfoVO.setMaxValue(maxValue);
                automaticInfoVO.setMinValue(minValue);
                automaticInfoVOList.add(automaticInfoVO);
                Date dateStart = TimeUnitEnums.WEEK.getCode().equals(secondDTO.getType()) ? DateUtils.getWeekStart(secondDTO.getRecordDate(), ZoneId.systemDefault()) : DateUtils.getMonthStart(secondDTO.getRecordDate(), ZoneId.systemDefault());
                Date dateEnd = TimeUnitEnums.WEEK.getCode().equals(secondDTO.getType()) ? DateUtils.getWeekEnd(secondDTO.getRecordDate(), ZoneId.systemDefault()) : DateUtils.getMonthEnd(secondDTO.getRecordDate(), ZoneId.systemDefault());
                averageVO.setDateStart(DateUtils.dateTimeChinese(dateStart) + "，" + DateUtils.queryWeekday(dateStart));
                averageVO.setDateEnd(DateUtils.dateTimeChinese(dateEnd) + "，" + DateUtils.queryWeekday(dateEnd));
            }
            average = Convert.toInt(total.stream().filter(num -> num != 0).mapToInt(Integer::intValue).average().orElse(0.0));
        }
        averageVO.setAverage(average);
        averageVO.setManualInfoVOS(manualInfoVOList);
        averageVO.setAutomaticInfoVOS(automaticInfoVOList);
        return averageVO;
    }

    @Override
    public ExerciseIntervalVO querySportHeartRate(GeneralSecondDTO secondDTO) {
        ExerciseIntervalVO exerciseIntervalVO = new ExerciseIntervalVO();
        int validTotalTime = 0;
        int totalTime = 0;
        int zone50Time = 0; // 热身放松 (50%)
        int zone60Time = 0; // 脂肪燃烧 (60%)
        int zone70Time = 0; // 心肺强化 (70%)
        int zone80Time = 0; // 耐力强化 (80%)
        int zone90Time = 0; // 无氧极限 (90%)
        List<RingExerciseDetail> ringExerciseDetailList = exerciseDetailMapper.querySportHeartRate(secondDTO);
        SysUser sysUser = sysUserMapper.queryUserHealthQuestion(SecurityUtils.getUserId());
        for (RingExerciseDetail ringExerciseDetail : ringExerciseDetailList){
            if(ringExerciseDetail != null && sysUser != null && sysUser.getBirthday() != null){
                exerciseIntervalVO.setTotalDuration(DateUtils.convertSecondsToChinese(Convert.toInt(ringExerciseDetail.getValidTime())));
                String[] hrvInfos = ringExerciseDetail.getHrList().replace("null", "0").replace("255", "0").split(",");//转成String数组
                List<Integer> hrvInfoList = Arrays.stream(hrvInfos).map(Integer::parseInt).collect(Collectors.toList());
                if(hrvInfoList.size() > 0){
                    Map<String, Integer> mapResult = calculateTimePerInterval(DateUtils.calculateAge(sysUser.getBirthday()),hrvInfoList,Convert.toDouble(ringExerciseDetail.getValidTime()));
                    totalTime += mapResult.get("totalTime");
                    zone50Time += mapResult.get("zone50Time"); // 热身放松 (50%)
                    zone60Time += mapResult.get("zone60Time"); // 脂肪燃烧 (60%)
                    zone70Time += mapResult.get("zone70Time"); // 心肺强化 (70%)
                    zone80Time += mapResult.get("zone80Time"); // 耐力强化 (80%)
                    zone90Time += mapResult.get("zone90Time"); // 无氧极限 (90%)
                }
            }
        }
        //总时长
        exerciseIntervalVO.setTotalDuration(DateUtils.convertSecondsToChinese(totalTime));

        //热身放松(50%-60%) 比例
        exerciseIntervalVO.setWarmUpRelaxRate(totalTime > 0 ? Math.round((double) zone50Time / totalTime * 100) : 0);
        //热身放松(50%-60%) 用时
        exerciseIntervalVO.setWarmUpRelaxTime(zone50Time > 0 ? DateUtils.convertSecondsToMinutesExact(zone50Time) : "");

        //脂肪燃烧(60%-70%) 比例
        exerciseIntervalVO.setFatBurningRate(totalTime > 0 ? Math.round((double) zone60Time / totalTime * 100) : 0);
        //脂肪燃烧(60%-70%) 用时
        exerciseIntervalVO.setFatBurningTime(zone60Time > 0 ? DateUtils.convertSecondsToMinutesExact(zone60Time) : "");

        //心肺强化(70%-80%) 比例
        exerciseIntervalVO.setHeartLungsRate(totalTime > 0 ? Math.round((double) zone70Time / totalTime * 100) : 0);
        //心肺强化(70%-80%) 用时
        exerciseIntervalVO.setHeartLungsTime(zone70Time > 0 ? DateUtils.convertSecondsToMinutesExact(zone70Time) : "");

        //耐力强化(80%-90%) 比例
        exerciseIntervalVO.setEnduranceReinforcementRate(totalTime > 0 ? Math.round((double) zone80Time / totalTime * 100) : 0);
        //耐力强化(80%-90%) 用时
        exerciseIntervalVO.setEnduranceReinforcementTime(zone80Time > 0 ? DateUtils.convertSecondsToMinutesExact(zone80Time) : "");

        //无氧极限(90%-100%) 比例
        exerciseIntervalVO.setAnaerobicLimitRate(totalTime > 0 ? Math.round((double) zone90Time / totalTime * 100) : 0);
        //无氧极限(90%-100%) 用时
        exerciseIntervalVO.setAnaerobicLimitTime(zone90Time > 0 ? DateUtils.convertSecondsToMinutesExact(zone90Time) : "");
        return exerciseIntervalVO;
    }

    @Override
    public SleepHeartRateVO querySleepHeartRate(GeneralSecondDTO secondDTO) {
        SleepHeartRateVO sleepHeartRateVO = queryAssemblyData(secondDTO.getDeviceSn(),secondDTO.getRecordDate());
        SleepHeartRateVO yesterdayResult = queryAssemblyData(secondDTO.getDeviceSn(),DateUtils.queryYesterday(secondDTO.getRecordDate()));
        SleepHeartRateVO heartRateVO = Convert.convert(SleepHeartRateVO.class,sleepHeartRateVO);
        heartRateVO.setAverageValue(sleepHeartRateVO.getAverage() - yesterdayResult.getAverage());
        heartRateVO.setMinHeartRateValue(sleepHeartRateVO.getMinHeartRate() - yesterdayResult.getMinHeartRate());
        heartRateVO.setFluctuationRangeValue(sleepHeartRateVO.getFluctuationRange() - yesterdayResult.getFluctuationRange());
        return heartRateVO;
    }

    /**
     * 组装数据
     */
    public SleepHeartRateVO queryAssemblyData(String deviceSn, Date dailyValue){
        SleepHeartRateVO sleepHeartRateVO = new SleepHeartRateVO();
        RingSleepDetail ringSleepDetail = sleepDetailMapper.querySleepInfoDetail(Builder.of(RingSleepDetailInfoDTO::new).
                with(RingSleepDetailInfoDTO::setDeviceSn, deviceSn).
                with(RingSleepDetailInfoDTO::setDailyValue, dailyValue).build());
        RingHeartRateInfo heartRateInfo = ringHeartRateInfoMapper.selectOneRingHeartRateInfo(Builder.of(RingHeartRateInfo::new).with(RingHeartRateInfo::setDeviceSn, deviceSn).with(RingHeartRateInfo::setDailyValue, dailyValue).build());
        int average = 0;
        int maxValue = 0;
        int minValue = 0;
        if(ringSleepDetail != null && heartRateInfo !=null){
            List<RingSleepHeartRateVO.RingSleepHeartRate> list = getSleepHeartRates(heartRateInfo.getDailyValue(),heartRateInfo.getTimeInterval(),heartRateInfo.getHeartRateList().replace("null", "0").replace("255","0"),ringSleepDetail);
            average = Convert.toInt(list.stream().filter(rate -> rate.getValue() != 0).mapToInt(rate -> rate.getValue()).average().orElse(0.0));
            maxValue = list.stream().filter(rate -> rate.getValue() != 0).mapToInt(rate -> rate.getValue()).max().orElse(0);
            minValue = list.stream().filter(rate -> rate.getValue() != 0).mapToInt(rate -> rate.getValue()).min().orElse(0);
        }
        sleepHeartRateVO.setAverage(average);
        sleepHeartRateVO.setAverageInfo(getAverageResult(average));
        sleepHeartRateVO.setMinHeartRate(minValue);
        sleepHeartRateVO.setMinHeartRateInfo(getMinHeartRateResult(minValue));
        sleepHeartRateVO.setFluctuationRange(maxValue-minValue);
        sleepHeartRateVO.setFluctuationRangeInfo(getFluctuationRangeResult(maxValue-minValue));
        return sleepHeartRateVO;

    }
    // 定义评级标准的描述
    private static final String EXCELLENT = "优秀";
    private static final String GOOD = "良好";
    private static final String OBSERVE = "待观察";
    private static final String ATTENTION = "需注意";
    private static final String POOR = "欠佳";
    private static String getAverageResult(int value) {
        if (value >= 50 && value <= 59) {
            return EXCELLENT;
        } else if ((value >= 45 && value <= 49) || (value >= 60 && value <= 64)) {
            return GOOD;
        } else if ((value >= 40 && value <= 44) || (value >= 65 && value <= 69)) {
            return OBSERVE;
        } else if ((value >= 35 && value <= 39) || (value >= 70 && value <= 79)) {
            return ATTENTION;
        } else if (value < 35 || value >= 80) {
            return POOR;
        }
        return "未知";
    }
    private static String getMinHeartRateResult(int value) {
        if (value >= 40 && value <= 49) {
            return EXCELLENT;
        } else if ((value >= 35 && value <= 39) || (value >= 50 && value <= 54)) {
            return GOOD;
        } else if ((value >= 30 && value <= 34) || (value >= 55 && value <= 59)) {
            return OBSERVE;
        } else if ((value >= 25 && value <= 29) || (value >= 60 && value <= 64)) {
            return ATTENTION;
        } else if (value < 25 || value >= 65) {
            return POOR;
        }
        return "未知";
    }
    private static String getFluctuationRangeResult(int value) {
        if (value <= 20) {
            return EXCELLENT;
        } else if (value >= 21 && value <= 30) {
            return GOOD;
        } else if (value >= 31 && value <= 40) {
            return OBSERVE;
        } else if (value >= 41 && value <= 50) {
            return ATTENTION;
        } else if (value >= 51) {
            return POOR;
        }
        return "未知";
    }
    /**
     * @param dateValue 时间
     * @param timeInterval 间隔
     * @param strValue 逗号隔开的字符串
     * @param sleepDetail 睡眠详情对象
     * @return 时间戳与心率的映射列表，按时间排序
     */
    public static List<RingSleepHeartRateVO.RingSleepHeartRate> getSleepHeartRates(Date dateValue,int timeInterval, String strValue, RingSleepDetail sleepDetail) {
        // 转换时间单位：秒 -> 毫秒
        long intervalMs = timeInterval * 60L * 1000L;
        // 获取睡眠时间段的时间戳
        long sleepStartMs = sleepDetail.getStartDate().getTime();
        long sleepEndMs = sleepDetail.getEndDate().getTime();
        // 心率数据起始时间戳
        long hrStartMs = dateValue.getTime();
        // 存储结果的有序映射
        List<RingSleepHeartRateVO.RingSleepHeartRate> list = new ArrayList<>();
        // 遍历所有心率数据点
        List<Integer> hrList = Arrays.stream(strValue.split(","))
                .map(String::trim) // 去除每个元素前后的空格
                .map(Integer::parseInt) // 转换为整数
                .collect(Collectors.toList());
        for (int i = 0; i < hrList.size(); i++) {
            // 计算当前心率数据点对应的时间戳
            long currentTimeMs = hrStartMs + (long)i * intervalMs;
            // 检查该时间点是否在睡眠期间内
            if (currentTimeMs >= sleepStartMs && currentTimeMs <= sleepEndMs) {
                int hrValue = hrList.get(i);
                // 仅添加有效心率值(排除0值)
                if (hrValue > 0) {
                    RingSleepHeartRateVO.RingSleepHeartRate sleepHeartRate = new RingSleepHeartRateVO.RingSleepHeartRate();
                    sleepHeartRate.setKey(DateUtils.calculateTimeAfterMinutes(DateUtil.date(currentTimeMs),0));
                    sleepHeartRate.setValue(hrValue);
                    list.add(sleepHeartRate);
                }
            }
        }
        return list;
    }

    @Override
    public  List<GeneralInfoListVO> queryHeartRateInfoList(GeneralSecondDTO secondDTO) {
        List<GeneralInfoListVO> list = new ArrayList<>();
        List<GeneralGroupVO> groupVOList = heartRateMapper.queryHeartRateDetailList(secondDTO);
        for (GeneralGroupVO group : groupVOList) {
            GeneralInfoListVO infoListVO = new GeneralInfoListVO();
//            infoListVO.setDateStart(group.getDateStart());
//            infoListVO.setDateEnd(group.getDateEnd());
            infoListVO.setDailyValue(group.getDailyValue());
            infoListVO.setWeekName(group.getWeekName());
            String groupData = group.getGroupData(); // 包含多条记录的JSON数组
            // 解析JSON数组为具体的实体类（假设有子实体类）
            if(groupData != null){
                JSONArray jsonArray = JSONArray.parseArray(groupData);
                List<JsonObjectVO> jsonObjectVOList = jsonArray.toJavaList(JsonObjectVO.class);
                jsonObjectVOList = jsonObjectVOList.stream().sorted(Comparator.comparingLong(JsonObjectVO::getId).reversed()).collect(Collectors.toList());
                infoListVO.setJsonObjectVOList(jsonObjectVOList);
            }
            list.add(infoListVO);
        }
        return list;
    }

    @Override
    public GeneralDetailListVO queryHeartRateDetail(Long id) {
        RingHeartRate ringHeartRate = heartRateMapper.selectRingHeartRateById(id);
        GeneralDetailListVO bloodOxygenDetailVO = Convert.convert(GeneralDetailListVO.class,ringHeartRate);
        bloodOxygenDetailVO.setGeneralValue(ringHeartRate.getHeartRate());
        bloodOxygenDetailVO.setWeek(DateUtils.queryWeekday(ringHeartRate.getDailyValue()));
        bloodOxygenDetailVO.setEndHm(DateUtils.convertDateTimeToHHMM(ringHeartRate.getEndTime()));
        return bloodOxygenDetailVO;
    }

    @Override
    public List<Integer> queryHeartRateSevenInfo(GeneralSecondDTO secondDTO) {
        List<RingHeartRate> detailList = heartRateMapper.queryHeartRateSevenInfo(secondDTO.getDeviceSn(),new Date());
        List<Integer> heartRates = detailList.stream().map(RingHeartRate::getHeartRate).collect(Collectors.toList());
        return heartRates;
    }

    /**
     * 区间上下限
     * 计算公式为：
     * 区间下限 BPM = 最大心率（220-实际年龄）× 区间百分比下限
     * 区间上限 BPM = 最大心率（220-实际年龄）× 区间百分比上限
     */
    public static Map<String,Integer> queryUpperLowerResult(Integer age, Double upperRate,Double lowerRate){
        Map<String,Integer> map = null;
        if(age > 0){
            map = new HashMap<>();
            map.put("upper",Convert.toInt((220 - age) * Convert.toDouble(upperRate/100)));
            map.put("lower",Convert.toInt((220 - age) * Convert.toDouble(lowerRate/100)));
        }
        return map;
    }
    /**
     * 整合区间心率
     * @param age
     * @param hrvInfoList
     * @param validTime
     * @return
     */
    public static Map<String, Integer> calculateTimePerInterval(Integer age, List<Integer> hrvInfoList, Double validTime) {
        int totalTime = 0;
        int zone50Time = 0; // 热身放松 (50%)
        int zone60Time = 0; // 脂肪燃烧 (60%)
        int zone70Time = 0; // 心肺强化 (70%)
        int zone80Time = 0; // 耐力强化 (80%)
        int zone90Time = 0; // 无氧极限 (90%)
        Map<String, Integer> mapResult = new HashMap<>();
        int number = hrvInfoList.size();
        if (number == 0) return null;
        //热身放松(50%-60%)
        Map<String,Integer>  warmUpRelaxMap = queryUpperLowerResult(age,Convert.toDouble(50),Convert.toDouble(60));
        //脂肪燃烧(60%-70%)
        Map<String,Integer>  fatBurningMap = queryUpperLowerResult(age,Convert.toDouble(60),Convert.toDouble(70));
        //心肺强化(70%-80%)
        Map<String,Integer>  heartLungsMap = queryUpperLowerResult(age,Convert.toDouble(70),Convert.toDouble(80));
        //耐力强化(80%-90%)
        Map<String,Integer>  enduranceReinforcementMap = queryUpperLowerResult(age,Convert.toDouble(80),Convert.toDouble(90));
        //无氧极限(90%-100%)
        Map<String,Integer>  anaerobicLimitwarmUpRelaxMap = queryUpperLowerResult(age,Convert.toDouble(90),Convert.toDouble(100));
        // --- 2. 计算平均心率间隔 ---
        double averageIntervalSeconds = validTime / number;
        for (int heartRate : hrvInfoList) {
            // 跳过无效的心率值（例如0）
            if (heartRate <= 0) {
                continue;
            }
            // 根据心率值，累加到对应的区间
            if (heartRate >= warmUpRelaxMap.get("upper") && heartRate < warmUpRelaxMap.get("lower")) {
                zone50Time += averageIntervalSeconds;
                totalTime +=  averageIntervalSeconds;
            } else if (heartRate >= fatBurningMap.get("upper") && heartRate <  fatBurningMap.get("lower")) {
                zone60Time += averageIntervalSeconds;
                totalTime +=  averageIntervalSeconds;
            } else if (heartRate >= heartLungsMap.get("upper") && heartRate <  heartLungsMap.get("lower")) {
                zone70Time += averageIntervalSeconds;
                totalTime +=  averageIntervalSeconds;
            } else if (heartRate >= enduranceReinforcementMap.get("upper") && heartRate <  enduranceReinforcementMap.get("lower")) {
                zone80Time += averageIntervalSeconds;
                totalTime +=  averageIntervalSeconds;
            } else if (heartRate >= anaerobicLimitwarmUpRelaxMap.get("upper") && heartRate <  anaerobicLimitwarmUpRelaxMap.get("lower")) {
                zone90Time += averageIntervalSeconds;
                totalTime +=  averageIntervalSeconds;
            }
        }
        mapResult.put("totalTime", totalTime );
        mapResult.put("zone50Time", zone50Time); // 热身放松 (50%)
        mapResult.put("zone60Time", zone60Time); // 脂肪燃烧 (60%)
        mapResult.put("zone70Time", zone70Time); // 心肺强化 (70%)
        mapResult.put("zone80Time", zone80Time); // 耐力强化 (80%)
        mapResult.put("zone90Time", zone90Time); // 无氧极限 (90%)
        return mapResult;
    }

}
